/**
 * 颜色混合
 * @param {*} target 目标颜色
 * @param {*} mix 混合颜色（十六进制）
 * @param {*} weight 权重
 * @returns {String} 混合后颜色
 * @author wangyuan
 */
const colorMix = (target: string, mix: string, weight: number) => {
  weight = Math.max(Math.min(Number(weight), 1), 0)
  let r1 = parseInt(target.substring(1, 3), 16)
  let g1 = parseInt(target.substring(3, 5), 16)
  let b1 = parseInt(target.substring(5, 7), 16)
  let r2 = parseInt(mix.substring(1, 3), 16)
  let g2 = parseInt(mix.substring(3, 5), 16)
  let b2 = parseInt(mix.substring(5, 7), 16)
  let r = Math.round(r1 * (1 - weight) + r2 * weight)
  let g = Math.round(g1 * (1 - weight) + g2 * weight)
  let b = Math.round(b1 * (1 - weight) + b2 * weight)
  return '#' + ('0' + (r || 0).toString(16)).slice(-2) + ('0' + (g || 0).toString(16)).slice(-2) + ('0' + (b || 0).toString(16)).slice(-2)
}

/**
 * 更改css变量
 * @param {*} color 颜色（十六进制）
 * @param {*} varCss css变量名
 * @author wangyuan
 */
const colorChange = (color: string, varCss = '--el-color-primary') => {
  const el = document.documentElement
  el.style.setProperty(varCss, color)
  el.style.setProperty(`${varCss}-dark`, color)
  // 这里是覆盖原有颜色的核心代码
  const mixWhite = '#ffffff'
  const mixBlack = '#000000'
  if (varCss.indexOf('--el-color') > -1 || varCss.indexOf('--theme-color') > -1) {
    for (let i = 1; i < 10; i += 1) {
      el.style.setProperty(`${varCss}-light-${i}`, colorMix(color, mixWhite, i * 0.1))
      el.style.setProperty(`${varCss}-dark-${i}`, colorMix(color, mixBlack, i * 0.1))
    }
  }
}

/**
 * 初始化颜色变量
 * @author y.wang
 */
const initColors = () => {
  // theme
  colorChange('#0275ff', '--theme-color')
  // success
  colorChange('#17ce8a', '--theme-color-success')
  // warning
  colorChange('#f5c44c', '--theme-color-warning')
  // danger
  colorChange('#ff854d', '--theme-color-danger')
  // error
  colorChange('#ff854d', '--theme-color-error')
  // info
  colorChange('#909399', '--theme-color-info')
}

/**
 * 变更主题
 * @param {*} color 颜色（十六进制）
 * @author y.wang
 */
const themeChange = (color: string) => {
  colorChange(color)
  colorChange(color, '--theme-color')
}

export { initColors, themeChange }
